package com.lw.system.controller;

import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;

import org.hibernate.validator.constraints.Range;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.lw.common.basemodel.Json;
import com.lw.common.web.controller.base.BasicController;
import com.lw.system.model.User;
import com.lw.system.model.valid.First;

import io.swagger.annotations.ApiOperation;

/**
 * 
 * @Description: hibernate-validation验证测试类
 * @author wei.liu
 * @date 2016年12月23日 下午3:35:01
 * @version V1.0
 */
// @Validated // 如果继承Basecontroller 就会有问题不知道为什么
// 共有三种方法做数据校验
// 第一种，是hibernate原生验证 ：对应test1
// 第二种，spring 集成hibernate验证： 对应test2
// 第三种， 是非实体类的参数验证 这种方法验证：对应test3
// 1.必须在类上面加上@Validated注解
// 2.必须配置MethodValidationPostProcessor(如：com.lw.system.util.configuration.ValidationConfig)
// 3,必须在异常捕捉
// 注意：第三种方式 如果继承Basecontroller 就会有问题，该类下所有的方法映射都没有了，访问时会出现404，不知道为什么
// 注意：第三种方式 继承BasicController 却没有问题
@RestController
@Validated
public class ValidController extends BasicController {

	@ApiOperation(value = "hibernate原生验证测试", httpMethod = "GET", notes = "显示用户")
	@RequestMapping(value = "/index/test1", method = RequestMethod.GET)
	public Json test1(@Valid User user, BindingResult result) {
		if (result.hasErrors()) {
			return setFailed(result.getAllErrors().get(0).getDefaultMessage());
		}
		return setSimpleSuccess(user);
	}

	@ApiOperation(value = "spring验证测试", httpMethod = "GET", notes = "显示用户")
	@RequestMapping(value = "/index/test2", method = RequestMethod.GET)
	public Json test2(@Validated User user) {
		return setSimpleSuccess(user);
	}

	@RequestMapping(value = "/index/test3", method = RequestMethod.GET)
	public String test3(
			@Range(min = 1, max = 9, message = "年级只能从1-9") @RequestParam(name = "grade", required = true) int grade,
			@Min(value = 1, message = "班级最小只能1") @Max(value = 99, message = "班级最大只能99") @RequestParam(name = "classroom", required = true) int classroom) {
		return "" + grade + classroom;
	}

	/**
	 * 
	 * @Title: test4
	 * @Description: 这个是分组测试
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/index/test4", method = RequestMethod.GET)
	public Json test4(@Validated({ First.class }) User user) {
		return setSimpleSuccess(user);
	}

}
